<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">邀请用户</text>
			<view class="match-info">
				<text class="match-title">{{matchInfo.title || ''}}</text>
				<text class="match-date">{{scheduleInfo.date || ''}}</text>
			</view>
		</view>
		
		<!-- 搜索和筛选区域 -->
		<view class="search-section">
			<view class="search-bar">
				<view class="search-input-wrapper">
					<input 
						v-model="searchKeyword" 
						placeholder="搜索用户姓名或手机号" 
						@confirm="searchUsers"
						@input="onSearchInput"
						class="search-input"
						confirm-type="search"
					/>
					<view class="search-actions">
						<text class="clear-btn" v-if="searchKeyword" @click="clearSearch">✕</text>
						<button class="search-btn" @click="searchUsers">搜索</button>
					</view>
				</view>
			</view>
			
			<!-- 筛选条件 -->
			<view class="filter-section">
				<view class="filter-row">
					<text class="filter-label">裁判等级：</text>
					<picker mode="selector" :value="levelIndex" :range="levelOptions" @change="onLevelChange">
						<view class="picker-text">{{levelOptions[levelIndex] || '请选择'}}</view>
					</picker>
				</view>
				
				<view class="filter-row">
					<text class="filter-label">所属协会：</text>
					<picker mode="selector" :value="orgIndex" :range="orgOptions" @change="onOrgChange">
						<view class="picker-text">{{orgOptions[orgIndex] || '请选择'}}</view>
					</picker>
				</view>
				
				<view class="filter-row">
					<text class="filter-label">地区：</text>
					<picker mode="selector" :value="regionIndex" :range="regionOptions" @change="onRegionChange">
						<view class="picker-text">{{regionOptions[regionIndex] || '请选择'}}</view>
					</picker>
				</view>
			</view>
		</view>
		

		
		<!-- 用户列表 -->
		<view class="user-list-section">
			<view class="section-header">
				<text class="section-title">用户列表</text>
				<view class="batch-actions">
					<button class="batch-btn" @click="selectAll" v-if="!isAllSelected">全选</button>
					<button class="batch-btn" @click="clearSelection" v-else>取消全选</button>
					<text class="selected-count">已选择 {{selectedUsers.length}} 人</text>
				</view>
			</view>
			
			<view v-if="loading" class="loading-box">
				<view class="loading-content">
					<view class="loading-spinner"></view>
					<text class="loading-text">加载中...</text>
				</view>
			</view>
			
			<view v-else class="user-list">
				<view 
					class="user-item" 
					:class="{'selected': isUserSelected(item._id)}"
					v-for="item in userList" 
					:key="item._id"
					@click="toggleUserSelection(item)"
				>
					<view class="user-info">
						<view class="user-basic">
							<text class="user-name">{{item.real_name || item.nickname || '未设置'}}</text>
							<text class="user-level">{{item.level_name || '未认证'}}</text>
						</view>
						<view class="user-details">
							<text class="user-org">{{item.association || '未填写'}}</text>
							<text class="user-region">{{item.region || '未填写'}}</text>
						</view>
						<view class="match-score" v-if="item.matchScore">
							<text class="score-label">匹配度：</text>
							<text class="score-value">{{item.matchScore}}%</text>
						</view>
					</view>
					<view class="selection-indicator">
						<uni-icons 
							:type="isUserSelected(item._id) ? 'checkbox-filled' : 'circle'" 
							:color="isUserSelected(item._id) ? '#007aff' : '#c0c4cc'"
							size="24"
						/>
					</view>
				</view>
				
				<!-- 无数据提示 -->
				<view v-if="userList.length === 0" class="empty-box">
					<image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无符合条件的用户</text>
					<button class="retry-btn" @click="searchUsers">重新搜索</button>
				</view>
				
				<!-- 加载更多 -->
				<view v-if="userList.length > 0" class="load-more-wrapper">
					<view v-if="hasMore" class="load-more-btn" @click="loadMore">
						<text v-if="!loading">点击加载更多</text>
						<view v-else class="loading-content">
							<view class="loading-spinner"></view>
							<text class="loading-text">加载中...</text>
						</view>
					</view>
					<view v-else class="no-more-data">
						<text>没有更多数据了</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 邀请消息输入 -->
		<view class="message-section">
			<text class="section-title">邀请消息（可选）：</text>
			<textarea 
				v-model="invitationMessage" 
				placeholder="输入邀请消息，如：诚邀您参与本次比赛的裁判工作..."
				class="message-input"
				maxlength="200"
			></textarea>
			<text class="char-count">{{invitationMessage.length}}/200</text>
		</view>
		

		
		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
			<button class="cancel-btn" @click="goBack">取消</button>
			<button 
				class="invite-btn" 
				:disabled="selectedUsers.length === 0"
				@click="sendInvitations"
			>
				发送邀请 ({{selectedUsers.length}})
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 比赛信息
				scheduleId: '',
				matchId: '',
				matchInfo: {},
				scheduleInfo: {},
				
				// 搜索和筛选
				searchKeyword: '',
				levelIndex: -1,
				orgIndex: -1,
				regionIndex: -1,
				levelOptions: ['全部', '国际级', '国家级', '一级', '二级', '三级'],
				orgOptions: ['全部'],
				regionOptions: ['全部'],
				
				// 邀请设置
				invitationMessage: '',
				
				// 用户列表
				userList: [],
				selectedUsers: [],
				loading: false,
				page: 1,
				limit: 20,
				hasMore: true,
				loadMoreStatus: 'more',
				
				// 用户信息
				userInfo: {}
			}
		},
		computed: {
			isAllSelected() {
				return this.userList.length > 0 && this.selectedUsers.length === this.userList.length;
			}
		},
		onLoad(options) {
			this.scheduleId = options.scheduleId || '';
			this.matchId = options.matchId || '';
			
			if (!this.scheduleId || !this.matchId) {
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
				return;
			}
			
			this.getUserInfo();
			this.loadMatchInfo();
			this.loadFilterOptions();
			this.searchUsers();
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						this.userInfo = JSON.parse(userInfoStr);
					} catch (e) {
						console.error('解析用户信息失败', e);
					}
				}
			},
			
			// 加载比赛信息
			async loadMatchInfo() {
				try {
					// 获取日程信息
					const matchScheduleObject = uniCloud.importObject('match-schedule-object');
					const scheduleRes = await matchScheduleObject.getScheduleDetail({
						scheduleId: this.scheduleId
					});
					
					if (scheduleRes.code === 0) {
						this.scheduleInfo = scheduleRes.data;
						this.matchId = scheduleRes.data.match_id;
						
						// 获取比赛信息
						const matchObject = uniCloud.importObject('match-object');
						const matchRes = await matchObject.getMatchDetail({
							matchId: this.matchId
						});
						
						if (matchRes.code === 0) {
							this.matchInfo = matchRes.data;
						}
					}
				} catch (error) {
					console.error('加载比赛信息失败:', error);
				}
			},
			
			// 加载筛选选项
			async loadFilterOptions() {
				try {
					const userService = uniCloud.importObject('user-service');
					const res = await userService.getFilterOptions();
					
					if (res.code === 0) {
						this.orgOptions = ['全部', ...res.data.organizations];
						this.regionOptions = ['全部', ...res.data.regions];
					}
				} catch (error) {
					console.error('加载筛选选项失败:', error);
				}
			},
			
			// 搜索用户
			async searchUsers() {
				this.loading = true;
				this.page = 1;
				this.userList = [];
				this.hasMore = true;
				
				await this.loadUsers();
			},
			
			// 加载用户列表
			async loadUsers() {
				try {
					const userService = uniCloud.importObject('user-service');
					
					// 构建搜索条件
					const searchConditions = {
						keyword: this.searchKeyword,
						level: this.levelIndex > 0 ? this.levelOptions[this.levelIndex] : '',
						organization: this.orgIndex > 0 ? this.orgOptions[this.orgIndex] : '',
						region: this.regionIndex > 0 ? this.regionOptions[this.regionIndex] : '',
						page: this.page,
						limit: this.limit,
						// 为邀请功能添加匹配度计算
						matchInfo: {
							scheduleId: this.scheduleId,
							matchId: this.matchId,
							date: this.scheduleInfo.date,
							venue: this.scheduleInfo.venue
						}
					};
					
					const res = await userService.searchUsersForInvitation(searchConditions);
					
					if (res.code === 0) {
						if (this.page === 1) {
							this.userList = res.data.users || [];
						} else {
							this.userList = [...this.userList, ...(res.data.users || [])];
						}
						
						this.hasMore = res.data.hasMore;
						this.loadMoreStatus = this.hasMore ? 'more' : 'noMore';
					} else {
						uni.showToast({
							title: res.message || '搜索失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('搜索用户失败:', error);
					uni.showToast({
						title: '网络错误，请稍后再试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 加载更多
			async loadMore() {
				if (!this.hasMore || this.loading) return;
				
				this.page++;
				await this.loadUsers();
			},
			
			// 搜索输入处理
			onSearchInput(e) {
				this.searchKeyword = e.detail.value;
			},
			
			// 清除搜索
			clearSearch() {
				this.searchKeyword = '';
				this.searchUsers();
			},
			
			// 筛选条件变化
			onLevelChange(e) {
				this.levelIndex = e.detail.value;
				this.searchUsers();
			},
			
			onOrgChange(e) {
				this.orgIndex = e.detail.value;
				this.searchUsers();
			},
			
			onRegionChange(e) {
				this.regionIndex = e.detail.value;
				this.searchUsers();
			},
			

			
			// 用户选择相关
			isUserSelected(userId) {
				return this.selectedUsers.some(user => user._id === userId);
			},
			
			toggleUserSelection(user) {
				const index = this.selectedUsers.findIndex(u => u._id === user._id);
				if (index > -1) {
					this.selectedUsers.splice(index, 1);
				} else {
					this.selectedUsers.push(user);
				}
			},
			
			selectAll() {
				this.selectedUsers = [...this.userList];
			},
			
			clearSelection() {
				this.selectedUsers = [];
			},
			
			// 发送邀请
			async sendInvitations() {
				if (this.selectedUsers.length === 0) {
					uni.showToast({
						title: '请选择要邀请的用户',
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '确认邀请',
					content: `确定要邀请 ${this.selectedUsers.length} 位用户参与比赛吗？`,
					success: async (res) => {
						if (res.confirm) {
							await this.doSendInvitations();
						}
					}
				});
			},
			
			// 执行发送邀请
			async doSendInvitations() {
				uni.showLoading({
					title: '发送邀请中...'
				});
				
				try {
					const invitationService = uniCloud.importObject('invitation-service');
					const inviteeIds = this.selectedUsers.map(user => user._id);
					
					const res = await invitationService.sendInvitations({
						scheduleId: this.scheduleId,
						matchId: this.matchId,
						inviteeIds: inviteeIds,
						position: '待定',
						message: this.invitationMessage || '诚邀您参与此次比赛，期待您的参与！'
					});
					
					uni.hideLoading();
					
					if (res.code === 0) {
						uni.showToast({
							title: res.message || '邀请发送成功',
							icon: 'success'
						});
						
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.message || '邀请发送失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('发送邀请失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '网络错误，请稍后再试',
						icon: 'none'
					});
				}
			},
			

			
			// 返回
			goBack() {
				if (this.selectedUsers.length > 0) {
					uni.showModal({
						title: '确认返回',
						content: '返回后将丢失已选择的用户，确定返回吗？',
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack();
							}
						}
					});
				} else {
					uni.navigateBack();
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding-bottom: 120rpx;
	}
	
	.page-header {
		background: #fff;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		margin-bottom: 20rpx;
		
		.page-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 10rpx;
		}
		
		.match-info {
			.match-title {
				font-size: 28rpx;
				color: #666;
				margin-right: 20rpx;
			}
			
			.match-date {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
	
	.search-section {
		background: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		
		.search-bar {
			margin-bottom: 30rpx;
			
			.search-input-wrapper {
				display: flex;
				align-items: center;
				background: #f8f8f8;
				border-radius: 10rpx;
				padding: 15rpx 20rpx;
				
				.search-input {
					flex: 1;
					font-size: 28rpx;
					color: #333;
					background: transparent;
					border: none;
					outline: none;
				}
				
				.search-actions {
					display: flex;
					align-items: center;
					gap: 15rpx;
					
					.clear-btn {
						font-size: 32rpx;
						color: #ccc;
						padding: 5rpx;
					}
					
					.search-btn {
						padding: 10rpx 20rpx;
						background: #007aff;
						color: #fff;
						border-radius: 8rpx;
						font-size: 24rpx;
						border: none;
					}
				}
			}
		}
		
		.filter-section {
			.filter-row {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				
				.filter-label {
					width: 150rpx;
					font-size: 28rpx;
					color: #333;
				}
				
				.picker-text {
					flex: 1;
					padding: 15rpx 20rpx;
					background: #f8f8f8;
					border-radius: 10rpx;
					font-size: 28rpx;
					color: #666;
				}
			}
		}
	}
	

	
	.user-list-section {
		background: #fff;
		margin-bottom: 20rpx;
		
		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 30rpx 0;
			
			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.batch-actions {
				display: flex;
				align-items: center;
				gap: 20rpx;
				
				.batch-btn {
					padding: 10rpx 20rpx;
					background: #f0f0f0;
					color: #666;
					border-radius: 10rpx;
					font-size: 24rpx;
				}
				
				.selected-count {
					font-size: 24rpx;
					color: #007aff;
				}
			}
		}
		
		.loading-box {
			padding: 60rpx 0;
			
			.loading-content {
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 20rpx;
				
				.loading-spinner {
					width: 30rpx;
					height: 30rpx;
					border: 3rpx solid #f3f3f3;
					border-top: 3rpx solid #007aff;
					border-radius: 50%;
					animation: spin 1s linear infinite;
				}
				
				.loading-text {
					font-size: 28rpx;
					color: #666;
				}
			}
		}
		
		.load-more-wrapper {
			padding: 30rpx;
			text-align: center;
			
			.load-more-btn {
				padding: 20rpx 40rpx;
				background: #f8f8f8;
				border-radius: 25rpx;
				display: inline-block;
				font-size: 28rpx;
				color: #007aff;
			}
			
			.no-more-data {
				padding: 20rpx;
				
				text {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
		
		.user-list {
			padding: 20rpx 30rpx 30rpx;
			
			.user-item {
				display: flex;
				align-items: center;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #f0f0f0;
				
				&:last-child {
					border-bottom: none;
				}
				
				&.selected {
					background: #f0f8ff;
					margin: 0 -30rpx;
					padding: 30rpx;
					border-radius: 10rpx;
				}
				
				.user-info {
					flex: 1;
					
					.user-basic {
						display: flex;
						align-items: center;
						margin-bottom: 10rpx;
						
						.user-name {
							font-size: 32rpx;
							font-weight: bold;
							color: #333;
							margin-right: 20rpx;
						}
						
						.user-level {
							font-size: 24rpx;
							background: #e7f3ff;
							color: #007aff;
							padding: 4rpx 12rpx;
							border-radius: 12rpx;
						}
					}
					
					.user-details {
						display: flex;
						gap: 30rpx;
						margin-bottom: 10rpx;
						
						.user-org,
						.user-region {
							font-size: 24rpx;
							color: #999;
						}
					}
					
					.match-score {
						display: flex;
						align-items: center;
						
						.score-label {
							font-size: 24rpx;
							color: #666;
						}
						
						.score-value {
							font-size: 24rpx;
							color: #ff6b35;
							font-weight: bold;
						}
					}
				}
				
				.selection-indicator {
					margin-left: 20rpx;
				}
			}
		}
		
		.empty-box {
			padding: 100rpx 60rpx;
			text-align: center;
			
			.empty-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 30rpx;
			}
			
			.empty-text {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 40rpx;
				display: block;
			}
			
			.retry-btn {
				background: #007aff;
				color: #fff;
				padding: 20rpx 40rpx;
				border-radius: 50rpx;
				font-size: 28rpx;
			}
		}
	}
	
	.message-section {
		background: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		
		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
			display: block;
		}
		
		.message-input {
			width: 100%;
			min-height: 120rpx;
			padding: 20rpx;
			background: #f8f8f8;
			border-radius: 10rpx;
			font-size: 28rpx;
			line-height: 1.5;
			box-sizing: border-box;
		}
		
		.char-count {
			display: block;
			text-align: right;
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
		}
	}
	
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		display: flex;
		gap: 30rpx;
		
		.cancel-btn {
			flex: 1;
			padding: 25rpx 0;
			background: #f0f0f0;
			color: #666;
			border-radius: 10rpx;
			font-size: 32rpx;
		}
		
		.invite-btn {
			flex: 2;
			padding: 25rpx 0;
			background: #007aff;
			color: #fff;
			border-radius: 10rpx;
			font-size: 32rpx;
			
			&:disabled {
				background: #ccc;
				color: #999;
			}
		}
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
</style> 